﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using ADEVSO.Util;
using SmartParking.Bussiness;
using SmartParking.Data.Entities;
using SmartParking.Web.Models;

namespace SmartParking.Controllers
{
    [Authorize]
    public class MobileController : Controller
    {
        private bool IsMobileDevice()
        {
            string returnUrl = Request.QueryString["ReturnUrl"];
            if (Request.Browser.IsMobileDevice || ((returnUrl != null) && returnUrl.StartsWith("/Mobile/", StringComparison.OrdinalIgnoreCase)))
            {
                return true;
            }
            return false;
        }

        [AllowAnonymous]
        public ActionResult Index()
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Reservation");
            }
            else
            {
                return RedirectToAction("Login");
            }
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();

            // clear authentication cookie
            var cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
            cookie1.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie1);

            // clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
            var cookie2 = new HttpCookie("ASP.NET_SessionId", "");
            cookie2.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie2);

            return RedirectToAction("Login");
        }

        [AllowAnonymous]
        public ActionResult Login()
        {
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (SecurityManager.LoginUser(HttpContext, model.Email, model.Password, model.RememberMe))
                {
                    return RedirectToAction("Reservation");
                }
                else
                {
                    ModelState.AddModelError("", "Correo electrónico o contraseña incorrectas");
                }
            }
            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [AllowAnonymous]
        public ActionResult UserProfile()
        {
            if (User.Identity.IsAuthenticated)
            {
                ViewBag.Title = "Mi Perfil";
                ViewBag.SubmitButtonText = "Actualizar";
                return View(new UserProfileModel(User.Identity.Name));
            }
            else
            {
                ViewBag.Title = "Registro";
                ViewBag.SubmitButtonText = "Registrarse";
                return View();
            }            
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult UserProfile(UserProfileModel model)
        {
            if (ModelState.IsValid)
            {
                var isNew = model.UserId == 0; 
                if (SecurityManager.SaveUser(HttpContext, model.Email, model.Name, model.LastName, model.Password, model.ReceiveInfo, model.UserId))
                {
                    if (isNew)
                        return RedirectToAction("Reservation");
                }
                else
                {
                    //ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }
            return View(model);
        }

        public ActionResult Reservation()
        {
            return View(new ReservationModel());
        }

        public ActionResult Reservations()
        {
            return View(new ReservationListModel(HttpContext, ReservationListModel.ReservationListType.Session));
        }

        public ActionResult Account()
        {
            return View();
        }

        public ActionResult Orders()
        {
            ViewBag.Title = "Mis Ordenes";
            return View("List", new ListModel(new OrderListModel(email: User.Identity.Name)));
        }

        public ActionResult Order(string id)
        {
            ViewBag.Title = String.Format("Detalle de la Orden #{0}", id);
            if (SecurityManager.VerifyUserOrder(User.Identity.Name, id))
            {
                return View("ReservationsList", new ReservationListModel(HttpContext, ReservationListModel.ReservationListType.Order, orderId: id));
            }
            return RedirectToAction("Orders");
        }

        public ActionResult Preferences()
        {
            ViewBag.Title = "Mi Perfil";
            return View();
        }

        [HttpPost]
        public ActionResult RefreshModel(ReservationModel model)
        {
            //return RedirectToAction("RefreshModel", "Home", model);
            return new HomeController().RefreshModel(model);
        }

        [HttpPost]
        public ActionResult Reserve(ReservationModel model)
        {
            var result = new ReservationsModel(HttpContext);
            if (ModelState.IsValid)
            {
                try
                {
                    var reservation = ReservationModel.CreateOrderDetail(model);
                    ReservationsManager.AddLiveReservation(HttpContext.ApplicationInstance.Application, HttpContext.Session, Convert.ToInt32(Profile.PropertyValues[""]), reservation);
                    result.RefreshReservations();
                }
                catch (Exception ex)
                {
                    result.ErrorMessage = ex.Message;
                }
            }
            return Json(result);
        }

        [HttpPost]
        public ActionResult DeleteReservation(string id)
        {
            var ids = id.Split('-');
            var sessionId = ids[0];
            id = ids[1];
            ReservationsManager.RemoveLiveReservations(HttpContext.ApplicationInstance.Application, sessionId, Convert.ToInt32(id));
            return Reservations();
        }

        [AllowAnonymous]
        public ActionResult Dashboard()
        {
            return View(new DashboardReservationModel(HttpContext.ApplicationInstance.Application));
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
